<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入用户姓名" clearable v-model="queryInfo.query" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border style="width: 100%" stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 返回的数据中状态mg_state(true,false)需要加工一下(switch开关)再渲染到页面 -->
          <!-- 作用域插槽，让父组件(<el-table)能够加工子组件(<el-table-column)的数据 -->
          <!-- 固定写法:必须使用template标签填充插槽内容 -->
          <!-- 通过slot-scope属性可以获取到子组件(<el-table-column)绑定的属性所构成的对象,对象的名字是等号后的值，是自定义的 -->
          <!-- 通过 Scoped slot 可以获取到当前 row(行), column(列), $index 和 store（table 内部的状态管理）的数据 -->
          <template slot-scope="scope">
            <!-- <div>{{scope.row.mg_state}}</div> -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#ff4949"
              @change="statusChange(scope.row.id,$event)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改用户按钮 -->
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <!-- 删除用户按钮 -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              icon="el-icon-delete"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- layout 组件布局，子组件名用逗号分隔,表示要在页面渲染中使用的组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" width="40%" @close="closeReset">
      <el-form :model="addUserForm" :rules="addFormRules" ref="addUserFormRef" label-width="60px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addUserForm.username" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" autocomplete="off" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="modifyDialogFormVisible"
      width="40%"
      @close="modifyCloseReset"
    >
      <el-form
        :model="modifyUserForm"
        :rules="modifyFormRules"
        ref="modifyUserFormRef"
        label-width="60px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="modifyUserForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyUserForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="modifyUserForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="30%" @close="setRoleDialogClosed">
      <p>当前用户的姓名：{{userInfo.username}}</p>
      <p>当前用户的角色：{{userInfo.role_name}}</p>
      <!-- 下拉菜单组件 -->
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[3678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      // 获取用户列表的请求数据对象
      queryInfo: {
        query: "",
        // 当前页码
        pagenum: 1,
        // 每页显示数据条数
        pagesize: 10
      },
      // 用户列表
      userList: [],
      total: 0,
      // 控制添加用户对话框显示隐藏
      addDialogFormVisible: false,
      // 添加用户表单对象
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "用户名的长度在3~15个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名的长度在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 要修改的用户信息
      modifyUserForm: {},
      // 修改用户表单验证规则
      modifyFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 控制修改用户对话框显示隐藏
      modifyDialogFormVisible: false,
      // 控制分配角色对话框显示隐藏
      setRoleDialogVisible: false,
      // 要分配角色的用户对象
      userInfo: {},
      // 角色列表
      roleList: [],
      // 已选中的角色Id值
      selectedRoleId: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //   获取用户列表
    async getUserList() {
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo
      });
      // console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      //   console.log(this.userList);
      this.total = res.data.total;
    },
    // 搜索用户
    searchUser() {
      if (!this.queryInfo.query)
        return this.$message.error("请输入用户姓名查询");
      this.getUserList();
    },
    // 添加用户
    addUser() {
      // 添加用户表单验证并提交
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.post("users", this.addUserForm);
        // console.log(res);
        if (res.meta.status != 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.addDialogFormVisible = false;
        this.getUserList();
      });
    },
    // 关闭添加用户对话框重置表单
    closeReset() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 修改用户
    async handleEdit(index, row) {
      // console.log(index, row);
      // 其实 scope.row 已经可以获取到整行的数据了，但是当后台数据更改了，页面没有刷新时，
      // scope.row 获取的数据就不准确了，此时再进行修改数据提交会覆盖后台更新的数据，造成不好的后果
      // 所以推荐再用 id 发送请求保证获取的是最新的数据
      // this.modifyUserForm = row;
      const { data: res } = await this.$axios.get("users/" + row.id);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.modifyUserForm = res.data;
      // console.log(this.modifyUserForm);
      this.modifyDialogFormVisible = true;
    },
    // 关闭修改用户对话框重置表单
    modifyCloseReset() {
      this.$refs.modifyUserFormRef.resetFields();
    },
    // 修改用户表单验证并提交
    modifyUser() {
      // 修改用户表单验证
      this.$refs.modifyUserFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.put(
          "users/" + this.modifyUserForm.id,
          {
            email: this.modifyUserForm.email,
            mobile: this.modifyUserForm.mobile
          }
        );
        // console.log(res);
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.modifyDialogFormVisible = false;
        this.getUserList();
      });
    },
    // 删除用户
    async handleDelete(index, row) {
      // 弹框提示是否确认删除
      // await 实际是把返回的 promise 对象中的 resolve() 函数中的实参获取过来(不写 await ,则需要用 then 方法获取)
      // 对于错误函数 reject() 的实参，则需要 catch 方法捕获
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // 如果点击确定，则返回confirm字符串
      // 如果点击取消，则返回cancel(catch方法捕获)
      // console.log(confirmResult);
      //   console.log(index, row);
      if (confirmResult == "cancel")
        return this.$message({ type: "info", message: "已取消删除!" });
      const { data: res } = await this.$axios.delete("users/" + row.id);
      // console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserList();
    },
    // 每页显示条数变化时触发
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    // 当前页码发生变化时触发
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    // 用户状态改变回调
    async statusChange(id, newStatus) {
      //   console.log(id, newStatus);
      const { data: res } = await this.$axios.put(
        `users/${id}/state/${newStatus}`
      );
      //   console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 分配角色
    setRole(user) {
      this.userInfo = user;
      this.getRoleList();
      this.setRoleDialogVisible = true;
    },
    // 获取角色列表
    async getRoleList() {
      const { data: res } = await this.$axios.get("roles");
      // console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.roleList = res.data;
    },
    // 分配角色按钮提交
    async saveRoleInfo() {
      if (!this.selectedRoleId) return this.$message.error("请选择角色！");
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      });
      console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserList();
      this.setRoleDialogVisible = false;
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = "";
      this.userInfo = {};
    }
  }
};
</script>

<style lang="less" scoped>
</style>